#region Copyright & License
/* Tyng.Data
 * Copyright (c) 2007, Paul Tyng, All rights reserved.
 * Code licensed under the BSD License:
 * http://www.opensource.org/licenses/bsd-license.php
 * Downloaded from: http://code.google.com/p/tyngdata/
*/
#endregion

using System;
using System.ComponentModel;

namespace Tyng.Data
{
    /// <summary>
    /// A converter for abbreviated numbers in text
    /// </summary>
    /// <remarks> 
    /// This is typically used for financial data and other numbers where very large numbers are 
    /// abbreviated in to millions or billions using a trailing M or B respectively.
    /// </remarks>
    [Serializable]
    public sealed class AbbreviatedNumberConverter : IFieldConverter
    {
        private AbbreviatedNumberConverter() { }

        #region IFieldConverter Members

        object IFieldConverter.ConvertFromString(Type toType, string data)
        {
            if (string.IsNullOrEmpty(data)) throw new ArgumentNullException(data);

            decimal d;

            if (data.Length > 2 && char.IsLetter(data[data.Length - 1]))
            {
                char size = char.ToUpper(data[data.Length - 1]);
                data = data.Substring(0, data.Length - 1);

                d = decimal.Parse(data);

                switch (size)
                {
                    case 'B':
                        d *= 1000000000;
                        break;
                    case 'M':
                        d *= 1000000;
                        break;
                    case 'K':
                        d *= 1000;
                        break;
                }
            }
            else
                d = decimal.Parse(data);

            if(toType == typeof(decimal)) return d;

            DecimalConverter tc = new DecimalConverter();

            return tc.ConvertTo(d, toType);
         }

        #endregion

        private static AbbreviatedNumberConverter _default;

        /// <summary>
        /// The default instance of the converter.
        /// </summary>
        public static AbbreviatedNumberConverter Default
        {
            get
            {
                if (_default == null)
                    _default = new AbbreviatedNumberConverter();

                return _default;
            }
        }
    }
}
